package com.yun.zf.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yun.zf.admin.mapper.ZfHouseInfoMapper;
import com.yun.zf.admin.service.ZfHouseInfoRentService;
import com.yun.zf.admin.service.ZfHouseInfoSaleService;
import com.yun.zf.admin.service.ZfHouseInfoService;
import com.yun.zf.admin.service.ZfHouseScoreService;
import com.yun.zf.admin.util.ReflectionObjectUtil;
import com.yun.zf.common.admin.model.house.HouseInfo;
import com.yun.zf.common.app.domain.ZfHouseInfo;
import com.yun.zf.common.app.domain.ZfHouseInfoRent;
import com.yun.zf.common.app.domain.ZfHouseInfoSale;
import com.yun.zf.common.app.domain.ZfHouseScore;
import com.yun.zf.common.mapstruct.admin.HouseMapper;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 买卖租售维护信息表 服务实现类
 * </p>
 *
 * @author cj
 * @since 2021-03-01
 */
@Service
@Log
public class ZfHouseInfoServiceImpl extends ServiceImpl<ZfHouseInfoMapper, ZfHouseInfo> implements ZfHouseInfoService {
    @Autowired
    private ZfHouseInfoRentService rentService;
    @Autowired
    private ZfHouseInfoSaleService saleService;
    @Autowired
    private ZfHouseScoreService scoreService;
    @Autowired
    private ReflectionObjectUtil objectUtil;

    /**
     * 新增维护房源信息
     *
     * @param houseInfo
     * @return
     */
    @Override
    @Transactional
    public int addHouseInfo(HouseInfo houseInfo, int type, Long provinceCode, Long cityCode) {
        // 数组转换
        ZfHouseInfo zfHouseInfo = HouseMapper.INSTANCE.moToHouseInfo(houseInfo);
        zfHouseInfo.setProvinceCode(provinceCode);
        zfHouseInfo.setCityCode(cityCode);
        ZfHouseInfoRent houseInfoRent = null;
        ZfHouseInfoSale houseInfoSale = null;
        //1、 维护房源信息
        zfHouseInfo.setListingTime(new Date());
        zfHouseInfo.setCreateTime(new Date());
        int count = baseMapper.insert(zfHouseInfo);

        // 计算房源得分情况
        BigDecimal iscore = objectUtil.checkIsNull(zfHouseInfo, "com.yun.zf.common.app.domain.ZfHouseInfo");
        BigDecimal infod =new BigDecimal("0");
        //2 、 如果为出租，则补充出租信息
        if (type == 1) {
            houseInfoRent = HouseMapper.INSTANCE.moToHouseInfoRent(houseInfo);
            houseInfoRent.setCreateTime(new Date());
            houseInfoRent.setProvinceCode(provinceCode);
            houseInfoRent.setCityCode(cityCode);
          houseInfoRent =  rentService.addHouseInfoRent(houseInfoRent);
            BigDecimal rentscore = objectUtil.checkIsNull(houseInfoRent, "com.yun.zf.common.app.domain.ZfHouseInfoRent");
            infod= (iscore.add(rentscore)).divide(new BigDecimal("2"), 2, BigDecimal.ROUND_HALF_UP);
        }
        if (type == 2) {
            houseInfoSale = HouseMapper.INSTANCE.moToHouseInfoSale(houseInfo);
            houseInfoSale.setCreateTime(new Date());
            houseInfoSale.setProvinceCode(provinceCode);
            houseInfoSale.setCityCode(cityCode);
            houseInfoSale=  saleService.addHouseInfoSale(houseInfoSale);
            // 计算二手房得分
            BigDecimal salescore = objectUtil.checkIsNull(houseInfoSale, "com.yun.zf.common.app.domain.ZfHouseInfoSale");
            infod= (iscore.add(salescore)).divide(new BigDecimal("2"), 2, BigDecimal.ROUND_HALF_UP);
        }
        // 计算房源得分情况
        calculateScore(zfHouseInfo,infod, zfHouseInfo.getBasicId(), cityCode, provinceCode);
        return count;
    }

    /**
     * 补充维护信息
     *
     * @param houseInfo
     * @return
     */
    @Override
    @Transactional
    public int motifyHouseInfo(HouseInfo houseInfo, int type, Long provinceCode, Long cityCode) {
        ZfHouseInfo zfHouseInfo = HouseMapper.INSTANCE.moToHouseInfo(houseInfo);
        ZfHouseInfoRent houseInfoRent = null;
        ZfHouseInfoSale houseInfoSale = null;
        int count = 0;
        QueryWrapper<ZfHouseInfo> houseInfoQueryWrapper = new QueryWrapper<>();
        houseInfoQueryWrapper.lambda().eq(ZfHouseInfo::getCityCode, cityCode)
                .eq(ZfHouseInfo::getProvinceCode, provinceCode)
                .eq(ZfHouseInfo::getId, zfHouseInfo.getId()).orderByAsc(ZfHouseInfo::getCreateTime);
        ZfHouseInfo info = baseMapper.selectList(houseInfoQueryWrapper).get(0);
        // 将前台传入的值赋值给原数据库中的值在做保存
        BeanUtil.copyProperties(zfHouseInfo, info);
        count = baseMapper.update(info, houseInfoQueryWrapper);

        // 计算房屋信息得分
        BigDecimal iscore = objectUtil.checkIsNull(info, "com.yun.zf.common.app.domain.ZfHouseInfo");
        BigDecimal infod =new BigDecimal("0");
        //2 、 如果为出租，则补充出租信息
        if (type == 1) {
            houseInfoRent = HouseMapper.INSTANCE.moToHouseInfoRent(houseInfo);
            houseInfoRent.setCityCode(cityCode);
            houseInfoRent.setProvinceCode(provinceCode);
            houseInfoRent = rentService.motifyRent(houseInfoRent);
            // 计算租赁得分
            BigDecimal rentscore = objectUtil.checkIsNull(houseInfoRent, "com.yun.zf.common.app.domain.ZfHouseInfoRent");
            infod= (iscore.add(rentscore)).divide(new BigDecimal("2"), 2, BigDecimal.ROUND_HALF_UP);

        }
        if (type == 2) {
            houseInfoSale = HouseMapper.INSTANCE.moToHouseInfoSale(houseInfo);
            houseInfoSale.setCityCode(cityCode);
            houseInfoSale.setProvinceCode(provinceCode);
            houseInfoSale = saleService.motifyHouseInfoSale(houseInfoSale);
            // 计算二手房得分
            BigDecimal salescore = objectUtil.checkIsNull(houseInfoSale, "com.yun.zf.common.app.domain.ZfHouseInfoSale");
            infod= (iscore.add(salescore)).divide(new BigDecimal("2"), 2, BigDecimal.ROUND_HALF_UP);
        }
        // 计算房源得分情况
        calculateScore(info,infod, zfHouseInfo.getBasicId(), cityCode, provinceCode);

        return count;
    }

    /**
     * 获取房源信息
     */
    @Override
    public HouseInfo getHouseInfoById(Long basicId, Long provinceCode, Long cityCode) {
        QueryWrapper<ZfHouseInfo> houseInfoQueryWrapper = new QueryWrapper<>();
        houseInfoQueryWrapper.lambda().eq(ZfHouseInfo::getCityCode, cityCode)
                .eq(ZfHouseInfo::getProvinceCode, provinceCode)
                .eq(ZfHouseInfo::getBasicId, basicId);
        ZfHouseInfo houseInfos = baseMapper.selectOne(houseInfoQueryWrapper);
        ZfHouseInfoRent rent = rentService.getHouseInfoRent(basicId, provinceCode, cityCode);
        ZfHouseInfoSale sale = saleService.getHouseInfoSale(basicId, provinceCode, cityCode);
        HouseInfo houseInfo = HouseMapper.INSTANCE.houseInfoToMo(houseInfos);
        HouseInfo houseInfo2 = HouseMapper.INSTANCE.houseInfoRentToMo(rent);
        HouseInfo houseInfo3 = HouseMapper.INSTANCE.houseInfoSaleToMo(sale);
        // 将多个属性合并到同一个对象上返回给前端使用
        if (houseInfo3 != null && houseInfo != null) {
            BeanUtil.copyProperties(houseInfo3, houseInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        }
        if (houseInfo2 != null && houseInfo != null) {
            BeanUtil.copyProperties(houseInfo2, houseInfo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        }
        return houseInfo;
    }


    public void calculateScore(ZfHouseInfo info,BigDecimal infod, Long basicId, Long cityCode, Long provCode) {
       // 补充信息中 装修权重占20%，推荐权重占30%，标签30%，家具占5%,家电5%，车位5%，房屋设备5%
        ZfHouseScore houseScore = new ZfHouseScore();
            // 装修 20%（豪装100%, 精装80%，简装60%，毛坯30%）
            // 如果是出租装修会有权重，出售则没有装修权重
            BigDecimal zx = new BigDecimal("0");
            switch (info.getFixtures()) {
                case "hz":
                    zx = new BigDecimal("1");
                    break;
                case "jz":
                    zx = new BigDecimal("0.8");
                    break;
                case "jian":
                    zx = new BigDecimal("0.6");
                    break;
                case "mp":
                    zx = new BigDecimal("0.3");
                    break;
            }
          BigDecimal zxScore = new BigDecimal("2").multiply(zx);
        // 推荐权重占30%
        BigDecimal rScore = new BigDecimal("0");
        if ("Y".equals(info.getIsRecommend())&&StringUtils.isNotBlank(info.getRecommendReason())) {
            rScore= new BigDecimal("3");
        }
        // 标签权重20%
        BigDecimal tagScore = new BigDecimal("2");
        if (StringUtils.isNotBlank(info.getTags())) {
            JSONArray array = JSONArray.parseArray(info.getTags());
          if (array.size()<=2){
              tagScore.multiply(new BigDecimal("0.3"));
          } else if (array.size()>2&& array.size()<4){
              tagScore.multiply(new BigDecimal("0.5"));
          } else {
              tagScore.multiply(new BigDecimal("1"));
          }
        }
        BigDecimal jj = new BigDecimal("0");
        if (StringUtils.isNotBlank(info.getFurniture())){
            jj = new BigDecimal("0.5");
        }
        BigDecimal jd = new BigDecimal("0");
        if (StringUtils.isNotBlank(info.getElectricappliance())){
            jd = new BigDecimal("0.5");
        }
        BigDecimal sb = new BigDecimal("0");
        if (StringUtils.isNotBlank(info.getEquipment())){
            sb = new BigDecimal("0.5");
        }
        BigDecimal cw = new BigDecimal("0");
        if (info.getParking()>0){
            cw = new BigDecimal("0.5");
        }
        houseScore.setInfoScore(zxScore.add(rScore).add(tagScore).add(jj).add(jd).add(sb).add(cw));
        houseScore.setInfo(infod);
        houseScore.setBasicId(basicId);
        houseScore.setCityCode(cityCode);
        houseScore.setProvinceCode(provCode);
        // 更新房源分数
        scoreService.addOrUpdate(houseScore);

    }


}
